# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:views.py
@time:2020/09/08
"""
from django.db import transaction
from rest_framework import generics
from rest_framework.views import APIView

from apps.project_case.models import House
from apps.member.models import MemberRecord
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from apps.system.serializers import OptionDictSerializer
from apps.system.models import Option
from .serializers import HouseAppSeializer, HouseDetailAppSeializer
from .filters import HouseAppFilter


class ProjectCaseDictView(APIView):
    def get(self, request):
        ret = {
            'style': OptionDictSerializer(Option.objects.filter(type=Option.HOUSE_STYLE, enable=True),
                                          many=True).data
        }
        return response_ok(ret)


class ProjectCaseListView(generics.ListAPIView):
    '''案例列表'''
    queryset = House.objects.filter(delete=False, is_complete=True)
    serializer_class = HouseAppSeializer

    def filter_queryset(self, queryset):
        f = HouseAppFilter(self.request.GET, queryset=queryset)
        return f.qs


class ProjectCaseDetailView(generics.RetrieveAPIView):
    '''案例详情'''
    queryset = House.objects.filter(delete=False)
    serializer_class = HouseDetailAppSeializer


class ProjectCaseCollectView(APIView):
    '''收藏案例'''
    permission_classes = [IsMemberUser, ]

    def get(self, request, pk):
        try:
            house = House.get_instance_by_id(pk)
            with transaction.atomic():
                _, message = MemberRecord.collect_operate(house, self.request.user.member)
                return response_ok(message)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
